﻿// https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
// 637. 二叉树的层平均值

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <queue>

using namespace std;

// struct ListNode {
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
// };

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> result;
        queue<TreeNode*> que;
        
        if (root != nullptr)
            que.push(root);
        
        while (!que.empty()) {
            int size = que.size();
            double sum = 0;
            double average = 0;
            for (int i = 0; i < size; i++) {
                TreeNode* temp = que.front();
                que.pop();
                sum += temp->val;
                if (temp->left)
                    que.push(temp->left);
                if (temp->right)
                    que.push(temp->right);
            }
            average = sum / size;
            result.push_back(average);
        }
        return result; 
    }
};

int main() {
    Solution obj = Solution();
}